import { defineStore } from 'pinia'
import api from '../api'

export const useReviewFolderStore = defineStore('reviewFolders', {
  state: () => ({ tree: [], flat: [], loading: false, error: '' }),
  actions: {
    async load() {
      this.loading = true; this.error = ''
      try {
        const [treeRes, listRes] = await Promise.all([
          api.get('/api/review-folders/tree'),
          api.get('/api/review-folders')
        ])
        this.tree = treeRes.data
        this.flat = listRes.data
      } catch (e) { this.error = e?.response?.data?.detail || '加载复盘目录失败' }
      finally { this.loading = false }
    },
    async create(name, parent_id = null) { await api.post('/api/review-folders', { name, parent_id }); await this.load() },
    async rename(id, name, parent_id) { await api.put(`/api/review-folders/${id}`, { name, parent_id }); await this.load() },
    async remove(id) { await api.delete(`/api/review-folders/${id}`); await this.load() },
    async move(id, parent_id) {
      let item = this.flat.find(f => f.id === id)
      if (!item) { await this.load(); item = this.flat.find(f => f.id === id) }
      const name = item ? item.name : ''
      await api.put(`/api/review-folders/${id}`, { name, parent_id })
      await this.load()
    },
    async reorder(id, body) {
      await api.patch(`/api/review-folders/reorder/${id}`, body)
      await this.load()
    },
  }
})
